package org.lc.stk.service;

import java.util.List;
import java.util.Optional;

import org.lc.stk.model.Department;
import org.lc.stk.repository.DepartmentRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class DepartmentService {

    private final DepartmentRepository departmentRepository;

    public DepartmentService(DepartmentRepository departmentRepository) {
        this.departmentRepository = departmentRepository;
    }

    public List<Department> findAllNonDeleted() {
        return departmentRepository.findByDeletedFalse();
    }

    public Optional<Department> findById(Long id) {
        return departmentRepository.findById(id);
    }

    public Department save(Department department) {
        // 如果是新建部门，设置deleted为false
        if (department.getId() == null) {
            department.setDeleted(false);
        }
        return departmentRepository.save(department);
    }

    public void softDelete(Long id) {
        departmentRepository.findById(id).ifPresent(department -> {
            department.setDeleted(true);
            departmentRepository.save(department);
        });
    }

    public List<Department> findByParent(Department parent) {
        return departmentRepository.findByParentAndDeletedFalseOrderByOrderNumberAsc(parent);
    }

    public List<Department> findRootDepartments() {
        return departmentRepository.findByParentIsNullAndDeletedFalse();
    }

    public boolean existsByCode(String code) {
        return departmentRepository.existsByCodeAndDeletedFalse(code);
    }

    public boolean existsByNameAndParent(String name, Department parent) {
        return departmentRepository.existsByNameAndParentAndDeletedFalse(name, parent);
    }

    public List<Department> getDepartmentAndDescendants(Long departmentId) {
        return departmentRepository.findDepartmentAndDescendants(departmentId);
    }
}